package com.shyroke.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shyroke.entity.PiZhu;
import com.shyroke.entity.User;
import com.shyroke.entity.XiaoShuo;
import com.shyroke.entity.readRecord;
import com.shyroke.mapper.XiaoShuoMapper;
import com.shyroke.service.FansServiceI;
import com.shyroke.service.PiZhuServiceI;
import com.shyroke.service.ReadRecordServiceI;
import com.shyroke.service.UserServiceI;

@Controller
@RequestMapping(value = "xiaoshuoAction")
public class XiaoShuoAction {

	@Autowired
	private XiaoShuoMapper xiaoshuoMapper;

	@Autowired
	private ReadRecordServiceI readRecordService;

	@Autowired
	private PiZhuServiceI pizhuService;

	@Autowired
	private UserServiceI userSeriveI;
	
	@Autowired
	private FansServiceI fansServiceI;
	
	/**
	 * 保存小说的书签
	 * 
	 * @param selected
	 *            用户选中的文本
	 * @param xiaoshuoId
	 *            小说ID
	 * @return
	 */
	@RequestMapping(value = "saveShuqian")
	@ResponseBody
	public Map<String, Object> saveShuqian(@RequestParam(value = "selected", required = true) String selected,
			@RequestParam(value = "xiaoshuoId", required = true) Integer xiaoshuoId, HttpSession session) {

		Map<String, Object> resultMap = new HashMap<String, Object>();
		XiaoShuo xiaoshuo = xiaoshuoMapper.selectByPrimaryKey(xiaoshuoId);

		String content = xiaoshuo.getContent();

		// 找到用户选中的内容在小说中所对应的内容
		if (content.contains(selected)) {
			Document document = Jsoup.parse(content);
			Elements elements = document.getElementsByTag("p");
			Element targetELe = null;
			for (Element ele : elements) {
				if (ele.text().contains(selected)) {
					targetELe = ele;
					break;
				}
			}
			if (targetELe != null) {
				User user = (User) session.getAttribute("user");
				String maoID = targetELe.attr("id");

				readRecordService.deleteByOld(user.getId(), xiaoshuoId);
				readRecordService.insert(xiaoshuoId, Integer.valueOf(maoID), user.getId());

				resultMap.put("msg", "书签保存成功");

			} else {
				throw new RuntimeException("用户所选内容不匹配");
			}

		}else {
			//用户选择的内容不是小说的内容.
			resultMap.put("msg", "只能针对某一段落进行保存标签！！");
		}

		return resultMap;
	}

	/**
	 * 获取小说的书签
	 * 
	 * @param xiaoshuoId
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "getShuqian")
	@ResponseBody
	public Map<String, Object> getShuqian(@RequestParam(value = "xiaoshuoId") Integer xiaoshuoId, HttpSession session) {
		User user = (User) session.getAttribute("user");
		Map<String, Object> resultMap = new HashMap<>();

		readRecord readRecord = readRecordService.selectByXiaoshuoIdAndUserId(xiaoshuoId, user.getId());
		if(readRecord!=null) {
			resultMap.put("maoId", readRecord.getMaoid());
		}
		
		return resultMap;

	}

	/**
	 * 保存批注
	 * 
	 * @param pizhu
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "savePizhu")
	@ResponseBody
	public Map<String, Object> savePizhu(@RequestParam(value = "pContent") String pContent, PiZhu pizhu,
			HttpSession session) {
		Map<String, Object> resulstMap = new HashMap<>();

		User user = (User) session.getAttribute("user");
		pizhu.setUserid(user.getId());

		// 设置段落P的Id
		XiaoShuo xiaoshuo = xiaoshuoMapper.selectByPrimaryKey(pizhu.getXiaoshuoid());
		String xiaoshuoContent = xiaoshuo.getContent();

		if (xiaoshuoContent.contains(pContent)) {

			Document document = Jsoup.parse(xiaoshuoContent);
			Elements elements = document.getElementsByTag("p");
			Element targetELe = null;
			for (Element ele : elements) {
				if (ele.text().contains(pContent)) {
					targetELe = ele;
					break;
				}
			}
			if (targetELe != null) {
				String pID = targetELe.attr("id");

				pizhu.setPid(Integer.valueOf(pID));
				pizhuService.deleteByPID(pizhu.getXiaoshuoid(), user.getId(), Integer.valueOf(pID));
				pizhuService.insert(pizhu);

				resulstMap.put("msg", "批注保存成功");

			} else {
				throw new RuntimeException("用户所选内容不匹配");
			}

		}

		return resulstMap;
	}

	/**
	 * 获取某个用户的某本小说的所有批注
	 * 
	 * @param session
	 * @param xiaoshuoid
	 * @param otherUserId 如果不为空，则表示是其他用户访问的小说
	 * @return
	 */
	@RequestMapping(value = "showPizhu")
	@ResponseBody
	public Map<String, Object> showPizhu(HttpSession session, @RequestParam(value = "xiaoshuoid") Integer xiaoshuoid,
			@RequestParam(value="otherUserId",required=false)Integer otherUserId) {

		User user =null;
		
		Map<String, Object> resultMap = new HashMap<>();
		if(otherUserId!=null && otherUserId!=0) {   //说明是其他用户访问的小说
			user = userSeriveI.selectByUserId(otherUserId);
			resultMap.put("otherUserId", otherUserId);
			
		}else {
			user = (User) session.getAttribute("user");
		}
		

		List<PiZhu> pizhuList = pizhuService.selectByUserIdAndXiaoshuoID(user.getId(), xiaoshuoid);
		XiaoShuo xiaoshuo = xiaoshuoMapper.selectByPrimaryKey(xiaoshuoid);;
		String newContent = xiaoshuo.getContent();
		Document document = Jsoup.parse(newContent);
		for(PiZhu pizhu:pizhuList) {
			
			Integer pid = pizhu.getPid();
			
			Element ele = document.getElementById(pid+"");
			ele.attr("style", "color:red");
			//用有color:red样式的替换没有的
		}
		
		
		String content = document.toString();
		
		resultMap.put("newContent",content);
		return resultMap;
	}

	
	/**
	 * 获取批注内容
	 * @param selected
	 * @param xiaoshuoId
	 * @param session
	 * @param otherUserId 如果不为空，则说明是其他用户想要查看批注，otherUserId表示被查看用户的id
	 * @return
	 */
	@RequestMapping(value = "getPizhu")
	@ResponseBody
	public Map<String, Object> getPizhu(String selected, Integer xiaoshuoId, HttpSession session,
			@RequestParam(value="otherUserId",required=false)Integer otherUserId) {
		Map<String, Object> resultMap = new HashMap<>();
		User user = null;
		if(otherUserId!=null && otherUserId!=0) {
			user = userSeriveI.selectByUserId(otherUserId);
			resultMap.put("otherUserId", otherUserId);
			//只有关注了该用户才能查看该用户的批注
			User currenUser = (User)session.getAttribute("user");
			boolean isLook =  fansServiceI.isLook(currenUser.getId(),otherUserId);
			if(!isLook) {
				resultMap.put("errMsg", "必须先关注才能查看批注");
				return resultMap;
			}
			

		}else {
			user = (User) session.getAttribute("user");
		}
		

		// 获取Pid
		XiaoShuo xiaoshuo = xiaoshuoMapper.selectByPrimaryKey(xiaoshuoId);
		String xiaoshuoContent = xiaoshuo.getContent();

		Document document = Jsoup.parse(xiaoshuoContent);
		Elements elements = document.getElementsByTag("p");

		Element targetEle = null;
		for (Element ele : elements) {
			if (ele.text().contains(selected)) {
				targetEle = ele;
			}
		}

		if (targetEle != null) {
			String pid = targetEle.attr("id");
			
			PiZhu pizhu = pizhuService.selectByPid(user.getId(),Integer.valueOf(pid),xiaoshuoId);
			resultMap.put("pizhu", pizhu);
			
		}

		
		
		return resultMap;
	}

}
